package com.etc.interceptor;

import java.io.PrintWriter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;

import com.etc.util.MyJWTHutool;

import cn.hutool.json.JSONObject;

/**
 * 
 * @ClassName: JwtInterceptor 
 * @Description: TODO(这里用一句话描述这个类的作用) 
 * @author knowno  
 * @date 2022年4月11日 下午2:21:27 
 *
 */
public class JwtInterceptor implements HandlerInterceptor {

	Logger logger = LoggerFactory.getLogger(getClass());

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {

		logger.info("***************** 拦截器开始  prehandle: *****************");

		//获取前端传递过来的token
		String token = request.getHeader("token");
		
		logger.info("prehandle: token : " + token);
		//如果传递的token为空
		if (token == null) {
			// .....
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			PrintWriter out = null;
			JSONObject res = new JSONObject();
			res.put("code", 0);
			res.put("msg", "尚未登录或者登录信息失效");
			out = response.getWriter();
			out.append(res.toString());
			return false;
		}
		logger.info("prehandle: Referer : " + request.getHeader("Referer"));
		
		String username = MyJWTHutool.getusername(token);

		logger.info("prehandle: username : " + username);

		if (username == null) {
			response.setCharacterEncoding("UTF-8");
			response.setContentType("application/json; charset=utf-8");
			PrintWriter out = null;
			JSONObject res = new JSONObject();
			res.put("code", 0);
			res.put("msg", "尚未登录或者登录信息失效");
			out = response.getWriter();
			out.append(res.toString());
			return false;
		}

		//验证token是否有效
		if (MyJWTHutool.parseToken(token)) {
			return true;
		}

		return false;
	}

}
